package simpleparser

import (
	"errors"
	"fmt"
	"strconv"
)

/**
 * 计算语法树结果
 * @param node 语法树节点
 * @param prefix 打印前缀（缩进）
 */
func Calc(node *AstNode, prefix string) (int, error) {
	if node == nil {
		return 0, errors.New("calc node is nil")
	}

	fmt.Printf("%s Calculating:%s\n", prefix, AST_NODE_DESC[node.Type])

	var ret int

	switch node.Type {
	case LiteralInt:
		ret, _ = strconv.Atoi(node.Value)

	case ExprAdd, ExprSub:
		v1, err := Calc(node.Children[0], "\t"+prefix)
		if err != nil {
			return 0, err
		}

		v2, err := Calc(node.Children[1], "\t"+prefix)
		if err != nil {
			return 0, err
		}

		if node.Value == "+" {
			ret = v1 + v2
		} else {
			ret = v1 - v2
		}

	case ExprMul, ExprDiv:
		v1, err := Calc(node.Children[0], "\t"+prefix)
		if err != nil {
			return 0, err
		}

		v2, err := Calc(node.Children[1], "\t"+prefix)
		if err != nil {
			return 0, err
		}

		if node.Value == "*" {
			ret = v1 * v2
		} else {
			ret = v1 / v2
		}

	default:
		return 0, errors.New("unknown calc ops - node type")
	}

	fmt.Printf("%s %s Result:%d\n", prefix, AST_NODE_DESC[node.Type], ret)
	return ret, nil
}
